package cn.abellflower.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * @author gjs
 */
public class EwmUtil {

    private static final int BLACK = 0xFF000000;    
    private static final int WHITE = 0xFFFFFFFF;   
    private static final int LOGO_PART = 4;
    private static final int MARGIN = 0;
      
    /** 
     * 生成二维码前的配置信息 
     * @param content 生成二维码图片内容 
     * @param width   二维码图片的宽度 
     * @param height  二维码图片的高度 
     * @param errorCorrectionLevel  纠错级别
     * @return 配置信息
     */  
    public static BitMatrix setBitMatrix(String content, int width, int height,
                                         ErrorCorrectionLevel errorCorrectionLevel){
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel);
        hints.put(EncodeHintType.MARGIN, MARGIN);
        BitMatrix bitMatrix=null;
        try {  
            bitMatrix = new MultiFormatWriter()
            	.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }    
        return bitMatrix;  
    }

    /**
     * 生成二维码前的配置信息
     * @param content 生成二维码图片内容
     * @param width   二维码图片的宽度
     * @param height  二维码图片的高度
     * @return 配置信息
     */
    public static BitMatrix setBitMatrix(String content, int width, int height){
        return setBitMatrix(content,width,height,ErrorCorrectionLevel.H);
    }

      
    /** 
     * 将LOGO图片放在二维码中间（水印效果） 
     * 将生成的图片以流的形式输出到页面展示 
     * @param matrix          BitMatrix 
     * @param format          图片格式 
     * @param outStream       输出流 
     * @param logoPath        LOGO地址 
     * @throws IOException
     */  
    public static void megerToFile(BitMatrix matrix, String format,
                                   OutputStream outStream, String logoPath) throws IOException {
        BufferedImage image = toBufferedImage(matrix);    
        //1.加入LOGO水印效果  
        if(StringUtils.isNotBlank(logoPath)){
        	Graphics2D gs = image.createGraphics();    
            BufferedImage logoImg = ImageIO.read(new File(logoPath));    
            int width = image.getWidth() / LOGO_PART;
            int height = image.getHeight() / LOGO_PART;
            int x = (image.getWidth() - width) / 2;    
            int y = (image.getHeight() - height) / 2;    
            gs.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null);    
            logoImg.flush();    
            gs.dispose();    
        }  
        ImageIO.write(image, format, outStream);  
    }   
      
    public static BufferedImage toBufferedImage(BitMatrix matrix){
        int width = matrix.getWidth();    
        int height = matrix.getHeight();    
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);    
        for(int x = 0; x < width; x++){    
            for(int y = 0; y < height; y++){    
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);    
            }    
        }    
        return image;       
    }

    public static void createEwm(String content, String filePath, String fileName) {
        String format = "jpg";
        BitMatrix bitMatrix = setBitMatrix(content, 180 , 180);

        long t1 = System.currentTimeMillis();
        OutputStream outStream = null;
        try {
            String path = filePath + fileName + ".png";
            outStream = new FileOutputStream(new File(path));
            //暂时不使用LOGO图片
            megerToFile(bitMatrix, format, outStream, null);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(outStream != null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void main(String[] args) {
    	String content ="www.baidu.com"; 
    	String format = "jpg";  
        BitMatrix bitMatrix = setBitMatrix(content, 180 , 180);
        
        long t1 = System.currentTimeMillis();
        OutputStream outStream = null;  
        try {  
            String path="D:/"+System.currentTimeMillis()+".png";
            outStream = new FileOutputStream(new File(path));
            //暂时不使用LOGO图片  
            megerToFile(bitMatrix, format, outStream, null);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
        	if(outStream != null){
        		try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
        System.out.println(System.currentTimeMillis() - t1);
    	
	}
}
